package udptest

import (
	"bufio"
	"encoding/json"
	"github.com/iikira/iikira-go-utils/utils/converter"
	"log"
	"net"
	"os"
	"strings"
)

func NewClient(localAddr, serverAddr string) error {
	localUdpAddr, err := net.ResolveUDPAddr("udp", localAddr)
	if err != nil {
		return err
	}
	serverUdpAddr, err := net.ResolveUDPAddr("udp", serverAddr)
	if err != nil {
		return err
	}
	conn, err := net.DialUDP("udp", localUdpAddr, serverUdpAddr)
	if err != nil {
		log.Fatalln(err)
	}
	defer conn.Close()

	// reader
	go func() {
		msgBuf := make([]byte, 16*converter.KB)
		msg := &Msg{}
		n := 0
		for {
			n, err = conn.Read(msgBuf)
			if err != nil {
				log.Println(err)
				continue
			}

			err = json.Unmarshal(msgBuf[:n], msg)
			if err != nil {
				log.Printf("json unmarshal error: %s, content: %s\n", err, msgBuf[:n])
				continue
			}

			printN := 16
			if printN > len(msg.Data) {
				printN = len(msg.Data)
			}
			log.Printf("seq: %d, srcIp: %s, data len: %d, data[:%d]: %s\n", msg.Seq, msg.SrcIp, len(msg.Data), printN, msg.Data[:printN])
		}
	}()

	input := bufio.NewScanner(os.Stdin)
	for input.Scan() {
		line := input.Text()
		if strings.TrimSpace(line) == "" {
			line = "1"
		}

		_, err = conn.Write([]byte(line))
		if err != nil {
			log.Println(err)
			continue
		}

		log.Printf("Write %s to %s\n", line, serverAddr)
	}
	return nil
}
